// 密码登录组件
// src/pages/login/widgets/password/index.tsx
import styles from "@styles/login.module.scss";
import { EyeFill, EyeInvisibleFill } from "antd-mobile-icons";
import classNames from "classnames";
import useToggle from "@hooks/useToggle";
import {z} from "zod";
import {SubmitHandler, useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import {useEffect} from "react";
import {Toast} from "antd-mobile";
import {useLoginByPasswordMutation} from "@store/apiSlice/authApiSlice";
import {useTypedDispatch} from "@store/index";
import {useNavigate} from "react-router-dom";
import {saveAuth} from "@store/slices/authSlice";
// 表单状态类型
interface FormState {
    password: string;
    mobile: string;
    isAgree: boolean;
}
//模式验证器
const schema = z.object({
    mobile: z.string({
        invalid_type_error:"手机号参数类型错误",
        required_error:"请检查手机号字段名称是否正确"
    })
        .min(1,"请输入手机号")
        .regex(/^1[3-9]\d{9}$/, "手机号格式错误"),
    password: z
        .string({
            invalid_type_error:"密码参数类型错误",
            required_error: "请检查密码字段名称是否正确"
        })
        .regex(/^\w{8,24}$/,"密码需要6-24个字符"),
    isAgree: z.literal(true,{
        errorMap: ()=> ({message:"请勾选协议"})
    })
})
export default function Password() {
    // 控制密码是否显示
    const [visible, setVisible] = useToggle(false);
    const {register,handleSubmit,formState:{errors,isValid}} = useForm<FormState>({
        // 在用户输入的过程中实时触发验证
        mode: "onChange",
        // 状态默认值
        defaultValues: { password: "", mobile: "", isAgree: false },
        // 设置表单验证器
        resolver: zodResolver(schema),
    })
    useEffect(() => {
        if (typeof errors.isAgree !== "undefined") {
            Toast.show({ content: "请勾选我已同意" });
        }
    }, [errors.isAgree]);
    // 用于实现用户登录的方法
    const [loginByPassword] = useLoginByPasswordMutation();
    // 获取 dispatch 方法
    const dispatch = useTypedDispatch();
    // 获取路由对象
    const navigate = useNavigate();
    // 表单提交
    const onSubmit: SubmitHandler<FormState> = ({ mobile, password }) => {
        loginByPassword({mobile,password})
            .unwrap()
            .then((response)=>{
                //请求失败
                if(typeof response.success !== "undefined" && response.success ===false){
                    //消息提示
                    return Toast.show(response.message)
                }
                //请求成功，保存用户凭据
                dispatch(saveAuth(response.data))
                //消息提示
                Toast.show({
                    content: "登录成功",
                    afterClose: () => {
                        // 跳转到个人中心页面
                        navigate("/personal");
                    },
                });
            })
    };

  // 渲染视图
  return (
    <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
      <div className={styles.formItem}>
        <input type="text" placeholder="请输入手机号" className={styles.text}    {...register("mobile")}/>
          {errors.mobile && <p className={styles.msg}>{errors.mobile.message}</p>}
      </div>
      <div className={styles.formItem}>
        <input
          type={visible ? "text" : "password"}
          placeholder="请输入密码"
          className={styles.text}
          {...register("password")}
        />
        <div className={styles.right} onClick={setVisible}>
          {visible ? <EyeFill /> : <EyeInvisibleFill />}
        </div>
          {errors.password && <p className={styles.msg}>{errors.password.message}</p>}
      </div>
      <div className={styles.formItem}>
        <label className={styles.agree}>
          <input type="checkbox" {...register("isAgree")}/>
          <span>
            我已同意<a href="#"> 用户协议 </a>及<a href="#"> 隐私条款</a>
          </span>
        </label>
      </div>
      <button
        type="submit"
        className={classNames(styles.submit, { [styles.disabled]: !isValid })}
      >
        登录
      </button>
    </form>
  );
}
